<template>
  <div>
    <div>
      <el-row>
        <el-col >
          <div class="Chart">
            <el-row>
              <el-col style="margin-top: 16px;">
                <span style="margin-left: 10px;">销售漏斗(按创建时间)</span>
              </el-col>
              <el-col style="margin-top: 16px;" :span="19">
                <el-date-picker
                  style="margin-left: 10px;"
                  size="small"
                  v-model="time1"
                  type="daterange"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
                <el-cascader
                  v-model="selectDept"
                  size="small"
                  :options="dept"
                  :props="drop"
                  v-if="postLevel==1" @change="queryEmp"></el-cascader>
                <el-select size="small" v-model="selectEmp"style="margin-left:10px;" clearable placeholder="负责人" v-if="postLevel==1" value-key="employeesId">
                  <el-option v-for="e in emp" :label="e.empName" :key="e.employeesId" :value="e.employeesId"></el-option>
                </el-select>
                <el-button size="small" type="primary" style="margin-left:10px;" @click="searchFunnelInfo">搜索</el-button>
              </el-col>

              <el-col :span="11">
                <div ref="funnlShape" style=" height:480px;margin-top: 25px;"></div>
              </el-col>
              <el-col :span="13">
                <div class="funnlTable">
                  <el-table
                    border
                    :data="tableData"
                    style="width: 100%">
                    <el-table-column
                      prop="sppedContext"
                      label="阶段"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="number"
                      label="数量"
                    >
                    </el-table-column>
                    <el-table-column
                      label="转化率"
                      prop="pcPercent"
                    >
                      <template slot-scope="c">
                        {{c.row.pcPercent | formatNull}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="预期金额"
                    >
                      <template slot-scope="slot">
                        {{slot.row.amount|formatMoney}}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col style="margin-top: 12px;">
          <div class="Chart">
            <el-row>
              <el-col style="margin-top: 16px;">
                <span style="margin-left: 10px;">商机数量趋势分析</span>
              </el-col>
              <el-col style="margin-top: 16px;">
                <el-date-picker
                  v-model="selectYear"
                  type="year"
                  placeholder="选择年" size="small"    :picker-options="pickerOptions1"  format="yyyy年" style="margin-left: 10px;width:105px;" @change="getMonthinfo">
                </el-date-picker>
                <el-select  placeholder="选择月" size="small" style="margin-left: 10px;width:105px;"  v-model="selectMonth" value-key="monthId" clearable>
                  <el-option  v-for="month in  monthinfo" :label="month.monthValue" :value="month.monthId" :key="month.monthId"></el-option>
                </el-select>
                <el-cascader
                  v-model="selectDept1"
                  size="small"
                  :options="dept"
                  :props="drop"
                  v-if="postLevel==1" @change="queryEmp1"></el-cascader>
                <el-select size="small"  v-model="selectEmp1" style="margin-left:10px;" clearable placeholder="负责人" v-if="postLevel==1" value-key="employeesId">
                  <el-option v-for="e in emp1" :label="e.empName" :key="e.employeesId" :value="e.employeesId"></el-option>
                </el-select>
                <el-button size="small" type="primary" style="margin-left:10px;" @click="selectNumber">搜索</el-button>
              </el-col>
            </el-row>
            <div style="width:95%;margin:0 auto;">
              <div ref="brokenChart" style="height:420px;margin-top: 12px;overflow:hidden;"></div>
            </div>
            <el-row>
              <div class="tableNumber">
                <table border="1" style="border-collapse: collapse;border:2px solid rgba(0, 0, 0, .1);color:#606266;">
                  <tr style="height:40px">
                    <td v-for=" h in header" style="min-width: 80px;">{{h}}</td>
                  </tr>
                  <tr style="height:40px">
                    <td v-for=" a in addnum"  style="min-width: 80px;">{{a}}</td>
                  </tr>
                  <tr style="height:40px">
                    <td v-for=" w in winnum"  style="min-width: 80px;">{{w}}</td>
                  </tr>
                  <tr style="height:40px">
                    <td v-for=" i in winprobability"  style="min-width: 80px;">{{i}}</td>
                  </tr>
                </table>
              </div>
              <div style="height:30px;"></div>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>

  export default {
    data(){
      return{
        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          }
        },
        value2:'',
        selectYear:'',
        selectMonth:'',
        monthinfo:[],//有效月份

        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        time1:[],
        stageList:[],//所有阶段
        stageDate:[],//阶段下的商机数量,
        tableData: [],//
        showTime:false,//高级选项时间
        addCount:[],//新增商机数
        WinCount:[],//赢单数
        month:[],
        selectEmp:'',//选择员工
        selectDept:[],//选择部门
        dept:[],//部门
        emp:[],//员工
        postLevel:'',//角色级别
        drop:{
          value:'value',
          label:'label',
          children:'childrenDept',
          checkStrictly: true ,
        },
        selectDept1:[],
        selectEmp1:'',
        emp1:'',
        header:[],
        addnum:[],
        winnum:[],
        winprobability:[],
      }
    },
    created() {
      this.selectYear= new Date();
      this.authentication();
      this.all_stage();
      this.getMonthinfo();
      this.business_stage_number(JSON.parse(sessionStorage.getItem('user')).employeesId,'','');
      this.monthNumber(JSON.parse(sessionStorage.getItem('user')).employeesId,this.selectDept1,this.selectYear);
      this.winProbability(this.selectYear,0)
      },


    methods:{
      //验证用户身份
      authentication(){
        var id = JSON.parse(sessionStorage.getItem('user')).employeesId;//用户id
        //获取用户是否是一级角色
        this.$axios.get("http://localhost:8088/is_one_Role",
          {params:{
              empId:id
            }}).then(v=>{
          this.selectDept.push(v.data.deptId);
          this.selectDept1.push(v.data.deptId);
          this.queryEmp();
          this.queryEmp1();
          this.selectEmp = id;
          this.selectEmp1 = id;
          if(v.data.postLevel==1){//用户是一级角色
            //查询出能看到的部门信息
            this.$axios.get("http://localhost:8088/data",
              {params:{
                  psetId:3,
                  fatherDeptId:v.data.deptId
                }}).then(res=>{
                  this.dept = res.data;
                  this.postLevel = 1;
            }).catch();
          }
        }).catch();
      },
      //查询到部门下的员工
      queryEmp(){
        this.selectEmp = '';
        this.emp = [];
        console.log("部门id:"+this.selectDept[this.selectDept.length-1]);
        this.$axios.get("http://localhost:8088/dept_emp",
          {params:{
              deptId:this.selectDept[this.selectDept.length-1]
            }}).then(v=>{
          this.emp = v.data;
        }).catch();

      },
      //查询到的每月新增商机数和赢单数
      monthNumber(empId,deptId,year){
        this.$axios.get("http://localhost:8088/businessView/business_month_count",
          {params:{
              empId:empId,
              deptId:deptId,
              year:new Date(year).getFullYear()
            }}).then(v=>{
          this.month=[];
          //月份
          v.data.winMonthNumber.forEach(item=>{
            this.month.push(item.time);
          });
          //新增商机数
          this.addCount=[];
          v.data.addMonthCount.forEach(item=>{
            this.addCount.push(item.number);
          });
          //赢单数
          this.WinCount=[];
          v.data.winMonthNumber.forEach(item=>{
            this.WinCount.push(item.number);
          })

        }).catch();

      },
      //查询到的每日新增商机数和赢单数
      dayNumber(empId,deptId,year,month){
        this.$axios.get("http://localhost:8088/businessView/business_day_count",
          {params:{
              empId:empId,
              deptId:deptId,
              year:new Date(year).getFullYear(),
              month:month
            }}).then(v=>{
          this.month=[];
          //月份
          v.data.addDayCount.forEach(item=>{
            this.month.push(item.time);
          });
          //新增商机数
          this.addCount=[];
          v.data.addDayCount.forEach(item=>{
            this.addCount.push(item.number);
          });
          //赢单数
          this.WinCount=[];
          v.data.winDayCount.forEach(item=>{
            this.WinCount.push(item.number);
          })
        }).catch();
      },
      //查询到部门下的员工
      queryEmp1(){
        this.selectEmp1 = '';
        this.emp1 = [];
        console.log("部门id:"+this.selectDept1[this.selectDept.length1-1]);
        this.$axios.get("http://localhost:8088/dept_emp",
          {params:{
              deptId:this.selectDept1[this.selectDept1.length-1]
            }}).then(v=>{
          this.emp1 = v.data;
          console.log("sss:"+ this.emp1.length);
        }).catch();

      },
      //商机数量的查询
      selectNumber(){
        if(this.selectYear ==null){
          this.$message.error("请选择年份");
        }else if(this.selectEmp1 == '' && this.selectDept1 == ''){
         if(this.selectMonth != ''){
           this.dayNumber('','',this.selectYear,this.selectMonth);
           this.winProbability(this.selectYear,this.selectMonth);
         }else{
           this.monthNumber('','',this.selectYear);
           this.winProbability(this.selectYear,0);
         }
        }else if(this.selectMonth !=''){
          this.dayNumber(this.selectEmp1,this.selectDept1[this.selectDept1.length-1],this.selectYear,this.selectMonth);
          this.winProbability(this.selectYear,this.selectMonth);
        }else if(this.selectMonth ==''){
          this.monthNumber(this.selectEmp1,this.selectDept1[this.selectDept1.length-1],this.selectYear);
          this.winProbability(this.selectYear,0);
        }
      },
      //赢单率
      winProbability(year,month){
        this.$axios.get("http://localhost:8088/businessView/calculate_winning_rate",
          {params:{
                  year:new Date(year).getFullYear(),
                  month:month
              }}).then(res=>{
               this.header = res.data.header;
               this.addnum = res.data.addnum;
               this.winnum = res.data.winnum;
               this.winprobability = res.data.winprobability;
        }).catch();
      },
      //指定年份查询有效月份
      getMonthinfo(){
        if(this.selectYear!=null){
          this.$axios.get("http://localhost:8088/businessView/get_monthInfo",
            {
              params:{
                valueInfo:new Date(this.selectYear).getFullYear()
              }
            }).then(v=>{
              this.selectMonth = '';
              this.monthinfo=v.data;
            }
          ).catch()
        }else{
          this.selectMonth = '';
          this.monthinfo=[];
        }
      },
      searchFunnelInfo(){
        var time = '';
        console.log("aaa:");
        console.log(this.time1);
        if( this.time1 .length != 0 ){
          console.log("建判断")
          time = this.time1[0]+','+this.time1[1];
        }
        if(this.selectDept !=''){//按条件查询数据
          this.business_stage_number(this.selectEmp,this.selectDept[this.selectDept.length-1],time);
        }else{//查询当前用户自己的信息
          this.business_stage_number(JSON.parse(sessionStorage.getItem('user')).employeesId,0,time);
        }

      },
      //所有的阶段
      all_stage(){
        this.$axios.get("http://localhost:8088/businessView/all_stage").then(v=>{
          this.stageList=v.data;
        }).catch();
      },
      //各阶段下的商机数量
      business_stage_number(empId,deptId,time){
        this.$axios.get("http://localhost:8088/businessView/business_stage_number",
          {
            params:{
              empId:empId,
              deptId:deptId,
              time:time
            }
          }).then(v=>{
          this.stageDate=v.data.stageNumber;
          this.tableData=v.data.translation;

        }).catch();
      },
      saleFunnel() {//销售漏斗
        // 基于准备好的dom，初始化echarts实例
        let myChart = this.$echarts.init(this.$refs.funnlShape)
        myChart. setOption ({
          color: ['#73DDFF', '#73ACFF', '#FDD56A', '#FDB36A', '#FD866A', '#9E87FF', '#58D5FF'],
          tooltip: {
            trigger: 'item',
            formatter: "{b} : {c}"
          },
          legend: {
            data: this.stageList
          },
          series: [
            {
              name: '（整体）',
              type: 'funnel',
              left: '8%',
              width: '75%',
              label: {
                normal: {
                  formatter: '{b}: {c}'
                },
                emphasis: {
                  position:'inside',
                  formatter: '{b}: {c}'
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              itemStyle: {
                normal: {
                  opacity: 0.7
                }
              },
              data: this.stageDate
            },
          ]
        })
      },
      broken(){
        let myChart = this.$echarts.init(this.$refs.brokenChart);
        myChart.setOption ({
          title: {
            subtext: "数量"
          },
          tooltip: {
            trigger: "axis"
          },
          legend: {
            data: ["新增商机数", "赢单数"]
          },
          grid: {
            left: '5%',
            right: '3%'
          },
          toolbox: {
            show: true,
            feature: {
              dataZoom: {
                yAxisIndex: "none"
              },
              dataView: {
                readOnly: false
              },
              magicType: {
                type: ["line", "bar"]
              },
              restore: {},
              saveAsImage: {}
            }
          },
          dataZoom: [{
            startValue: this.month[0]
          },
            {
              type: "inside"
            }
          ],
          xAxis: {
            type: "category",
            boundaryGap: false,
            data:this.month
          },
          yAxis: {
            type: "value",
            axisLabel: {
              formatter: "{value}"
            }
          },
          series: [{
            name: "新增商机数",
            type: "line",
            data:  this.addCount,
            markPoint: {
              data: [{
                type: "max",
                name: "最大值"
              },
                {
                  type: "min",
                  name: "最小值"
                }
              ]
            },
            itemStyle: {
              color: "#5bd1db"
            },
            lineStyle: {
              width: 3
            }
          },
            {
              name: "赢单数",
              type: "line",
              data: this.WinCount,
              markPoint: {
                data: [{
                  type: "max",
                  name: "最大值"
                },
                  {
                    type: "min",
                    name: "最小值"
                  }
                ]
              },
              itemStyle: {
                color: "#00ef09"
              },
              lineStyle: {
                width: 3
              }
            }
          ]
        })
      }
    },
    mounted () {
      setTimeout(()=>{this.saleFunnel()},500) ;
      setTimeout(()=>{this.broken()},500) ;

    },

    watch:{
      stageDate(val){
        this.saleFunnel();
      },
      month(val){
        this.broken();
      }
    },
    filters: {
      formatMoney(val) {
        val = val.toString().replace(/\$|\,/g, "");
        if (isNaN(val)) {
          val = "0";
        }
        let sign = (val == (val = Math.abs(val)));
        val = Math.floor(val * 100 + 0.50000000001);
        let cents = val % 100;
        val = Math.floor(val / 100).toString();
        if (cents < 10) {
          cents = "0" + cents;
        }
        for (let i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
          val = val.substring(0, val.length - (4 * i + 3)) + "," + val.substring(val.length - (4 * i + 3));
        }
        return (((sign) ? "" : "-") + val + "." + cents);
      },
      formatNull(value){
        if(value != '' && value != undefined && value != null){
          return value;
        }else{
          return "0.00%"
        }
      }
    }
  }
</script>
<style scoped>
  .menu{
    width:86%;
    background: white;
    box-shadow:#ccc 0px 0px 10px;
  }
  .funnlTitle{
    padding:20px;
  }
  .row_style{
    margin-top:-12px;
  }
  .Chart{
    width:100%;
    background: white;
    box-shadow:#ccc 0px 0px 10px;
  }
  .funnlTable {
    border: 1px solid #EBEEF5;
    border-radius: 5px;
    margin-top: 25px;
    width: 98%;
  }
  .el-form-item {
    margin-bottom: 9px;
  }
  .el-date-picker__header {
    display: none;
  }
  .tableNumber{
    width:85%;
    margin: 0 auto;
    overflow:scroll;
    margin-top: 10px;

  }
  .tableNumber table{
    margin: 0 auto;
    text-align: center;
  }
 /* .tableNumber td{
    width:100px;
  }*/
</style>
